import 'package:flutter/material.dart';

import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../../resources/kq_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../button/kq_ink_well.dart';
import '../divider/kq_divider.dart';
import '../formItem/entity/kq_form_entity.dart';

class KqSpecialView extends StatefulWidget {
  const KqSpecialView(
      {super.key,
      required this.entity,
      this.minWidth = 60,
      this.maxWidth = 90,
      this.height,
      this.isSeparate = false,
      this.onTap});
  final KqFormEntity entity; //extraData:[KqFormBaseEntity]
  final double minWidth;
  final double maxWidth;
  final double? height;
  final bool isSeparate;
  final Function(KqFormEntity entity)? onTap;
  @override
  State<KqSpecialView> createState() => _KqSpecialViewState();
}

class _KqSpecialViewState extends State<KqSpecialView> {
  double top = 4;
  double autoheight = (TextPainter(
          maxLines: 1,
          textDirection: TextDirection.ltr,
          text: TextSpan(text: '高度', style: TextStyle(fontSize: 14 )))
        ..layout(
          maxWidth: double.infinity,
        ))
      .size
      .height;

//计算宽度
  Size handleTxtWidth(String txt) {
    TextPainter painter = TextPainter(
        locale: Localizations.localeOf(context),
        maxLines: 1,
        textDirection: TextDirection.ltr,
        text: TextSpan(text: txt, style: TextStyle(fontSize: 14 )))
      ..layout(
        maxWidth: double.infinity,
      );
    return painter.size;
  }

  //标签
  Widget renderTags(KqFormBaseEntity item, int index) {
    Size size = handleTxtWidth(item.valueForShow!);
    double left = 4;
    double width = size.width + left * 2;
    double iconWidth = 16;
    return KqInkWell(
        onTap: () {
          setState(() {
            if (widget.entity.extraData != null &&
                widget.entity.extraData.length > index) {
              widget.entity.extraData.removeAt(index);
            }
          });
        },
        child: Container(
            width: width > widget.maxWidth
                ? widget.maxWidth + iconWidth
                : width < widget.minWidth
                    ? widget.minWidth + iconWidth
                    : width + iconWidth,
            height: widget.height != null && widget.height! > 0
                ? widget.height
                : autoheight + top * 2,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(vertical: top, horizontal: left),
            decoration: BoxDecoration(
              color: KqThemeColors.bgF4,
              borderRadius: BorderRadius.all(Radius.circular(2)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Flexible(
                    child: Text(
                  item.valueForShow!.replaceAll('', '\u200b'),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style:
                      TextStyle(fontSize: 14, color: KqThemeColors.text26),
                )),
                Icon(
                  Icons.clear,
                  size: iconWidth,
                  color: KqThemeColors.text59,
                )
              ],
            )));
  }

//txt
  Widget renderTxt(String txt, {TextAlign? align}) {
    return Text(
      txt.replaceAll('', '\u200b'),
      textAlign: align ?? TextAlign.right,
      style: TextStyle(fontSize: 14, color: KqThemeColors.text59),
    );
  }

//允许编辑的状态下
  Widget renderWrap() {
    return Wrap(
      alignment: WrapAlignment.start,
      textDirection: TextDirection.rtl,
      spacing: 4,
      runSpacing: 4,
      children: List.generate(
          widget.entity.extraData != null
              ? (widget.entity.extraData as List).length
              : 0, (index) {
        KqFormBaseEntity base = widget.entity.extraData[index];
        return renderTags(base, index);
      }),
    );
  }

  //不允许编辑 但是一行一个
  Widget renderSeparate() {
    if (widget.entity.extraData == null ||
        (widget.entity.extraData as List).isEmpty) {
      return Container();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: (widget.entity.extraData as List).map((e) {
        int index = (widget.entity.extraData as List).indexOf(e);
        String txt = '、';
        if (index + 1 == (widget.entity.extraData as List).length) {
          txt = '';
        }
        KqFormBaseEntity item = e as KqFormBaseEntity;
        return renderTxt('${item.valueForShow}$txt', align: TextAlign.start);
      }).toList(),
    );
  }

  //不允许编辑
  Widget renderDetail() {
    return renderTxt(widget.entity.valueForShow ?? '');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(right: 10),
                margin: EdgeInsets.only(
                    top: widget.entity.paddingVertical ??
                        KqThemeManager.instance
                            .getConfig()
                            .formConfig
                            .paddingVertical ??
                        15,
                    bottom: widget.entity.paddingVertical ??
                        KqThemeManager.instance
                            .getConfig()
                            .formConfig
                            .paddingVertical ??
                        15),
                child: Row(
                  children: <Widget>[
                    ///是否必填
                    Container(
                      alignment: Alignment.centerRight,
                      padding: EdgeInsets.only(
                        right: 2,
                      ),
                      width: widget.entity.paddingHorizontal ??
                          KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .paddingHorizontal ??
                          16,
                      child: Text(
                        "*",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .mustInputFontSize ??
                                14,
                            color: widget.entity.mustInput
                                ? KqThemeColors.textRed
                                : KqThemeColors.bgTransparent),
                      ),
                    ),

                    /// 标题
                    LimitedBox(
                      maxWidth: KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .titleMaxWidth ??
                          200,
                      child: Text(
                        widget.entity.title,
                        maxLines: widget.entity.multiline ? null : 1,
                        overflow: widget.entity.multiline
                            ? null
                            : TextOverflow.ellipsis,
                        style: widget.entity.titleStyle ??
                            TextStyle(
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .titleFontSize ??
                                    16,
                                color: KqThemeColors.text26),
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                child: Container(
                  margin: EdgeInsets.symmetric(vertical: 10, horizontal: 8),
                  color: Colors.white,
                  child: widget.entity.editable
                      ? renderWrap()
                      : widget.isSeparate
                          ? renderSeparate()
                          : renderDetail(),
                ),
              ),
              Visibility(
                  visible: widget.entity.editable,
                  child: KqInkWell(
                    onTap: () {
                      if (widget.entity.onTap != null) {
                        widget.entity.onTap!(widget.entity);
                      }
                      if (widget.onTap != null) {
                        widget.onTap!(widget.entity);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.all(11),
                      child: Image.asset(
                        KqImages.commonIcXinzeng16Blue,
                        height: 20,
                        width: 20,
                        package: KqGlobal.packageName,
                      ),
                    ),
                  )),
            ],
          ),
          const KqDivider(),
        ],
      ),
    );
  }
}
